using System;
using Habanero.Base;
using Habanero.Base.Exceptions;
using Habanero.BO;

namespace FireStarterModeller.BO
{
    public class DMRelationshipSingleToSingleAKRule : IBusinessObjectRule
    {
        private DMRelationship _dmRelationship;

//        public DMRelationshipSingleToSingleAKRule(DMRelationship dmRelationship)
//        {
//            if (dmRelationship == null) throw new ArgumentNullException("dmRelationship");
//            _dmRelationship = dmRelationship;
//        }

        public bool IsValid()
        {
            throw new HabaneroApplicationException("The IsValid is no longer Valid you should use the IsValid(bo) method");
        }

        public bool IsValid(IBusinessObject bo)
        {
            _dmRelationship = (DMRelationship) bo;
            if (_dmRelationship.ClassDM == null) return true;
            if ((_dmRelationship.Cardinality == Cardinality.Multiple)) return true;
            DMRelationship reverseRelationship = (DMRelationship)_dmRelationship.ReverseRelationship;
            if ((reverseRelationship == null) || (reverseRelationship.Cardinality == Cardinality.Multiple)) return true;
            DMClass relatedClass = (DMClass)reverseRelationship.ClassDM;
            if (relatedClass == null) return true;
            return IsValidSingleRelationship();
        }

        private bool IsValidSingleRelationship()
        {
            DMRelationship reverseRelationship = (DMRelationship) _dmRelationship.ReverseRelationship;
             
            return !(_dmRelationship.HasAllAkProps() && reverseRelationship.HasAllAkProps());
        }

        public string Name
        {
            get { return "DMRelationshipSingleToSingleAK"; }
        }

        public string Message
        {
            get
            {
                return string.Format("One side of the relationship '{0}-{1}' on Classes '{2}-{3}' must be a Primary Key while the other must be an Alternate Key.", _dmRelationship, _dmRelationship.ReverseRelationship, _dmRelationship.ClassDM, _dmRelationship.RelatedClass);

                //return "One side of the Relationship '" + _dmRelationship
                //       + "' on Class '" + _dmRelationship.ClassDM + "' must be a Primary Key while the other must be an Alternate Key.";
            }
        }
        public ErrorLevel ErrorLevel
        {
            get { return ErrorLevel.Warning; }
        }
    }
}